<template>
  <div class="page">
    <div class="header">
      <h4>{{ $lang.move }}</h4>
      <span class="btn-cancel" @click="back">{{ $lang.cancel }}</span>
    </div>
    <div class="myFolder">
      <div class="inboxTitle-wrapper">
        <div class="left-side" @click="dialogPop">
          <img
            class="left-side-icon"
            :src="require('@/assets/oppo/home/all.svg')"
          />
          <p>{{ $lang.inbox }}</p>
        </div>

        <div class="right-side">
          <div
            class="right-icon-wraper"
            v-show="inboxChildFolderCount"
            @click="toggleTree"
          >
            <img
              class="right-icon"
              :src="
                isOpen
                  ? require('@/assets/oppo/home/list-arrow-up.svg')
                  : require('@/assets/oppo/home/list-arrow-down.svg')
              "
              alt=""
            />
          </div>
        </div>
      </div>
      <div
        class="inboxSubFolder"
        v-show="isOpen"
        v-for="item in inboxChildFolder"
        :key="item.id"
      >
        <TreeNavItem :treeData="item" :level="1"></TreeNavItem>
      </div>
    </div>
    <div class="folderTree">
      <TreeNav :treeData="folderTree"></TreeNav>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from "vuex";
import TreeNav from "@/components/TreeNav.vue";
import TreeNavItem from "./TreeNavItem.vue";
import { Dialog } from "vant";
import { isMobile } from "@/utils/helper";
import {
  sortMenuInOrder,
  // sortMenuInOrderEnglish
} from "@/config/menu.js";
export default {
  components: {
    TreeNav,
    TreeNavItem,
  },
  name: "FolderManage",
  data() {
    return {
      isOpen: false,
      inboxChildFolder: [],
      inboxChildFolderCount: 0,
      folderTree: [],
      sortMenuInOrder: sortMenuInOrder,
    };
  },
  computed: {
    ...mapGetters(["mailType", "currentFolderList", "checkboxSelectArr"]),
    id() {
      return this.$route.params.id;
    },
  },
  methods: {
    ...mapMutations([
      "SAVEMAILTYPE",
      "SAVEFOLDERINFO",
      "SAVECHECKBOXSELECTARR",
    ]),
    sortFolderInSpecifiedOrder(folderTree) {
      this.$nextTick(() => {
        let priorityArr = [];
        for (let i = 0; i < this.sortMenuInOrder.length; i++) {
          for (let j = 0; j < folderTree.length; j++) {
            if (this.sortMenuInOrder[i] === folderTree[j].displayName) {
              priorityArr.push(folderTree[j]);
            }
          }
        }
        // console.warn('priorityArr:',priorityArr)
        const priorityIds = priorityArr.map((item) => item.id);
        // console.warn('priorityIds:::',priorityIds)
        const set = new Set([...priorityIds]);
        let leftArr = [];
        folderTree.map((item) => {
          if (!set.has(item.id)) {
            leftArr.push(item);
          }
        });
        // console.warn('leftArr,',leftArr)
        let finalArr = [...priorityArr, ...leftArr];
        finalArr.splice(0, 1);
        this.folderTree = [...finalArr];
        this.$toast.clear();
      });
    },

    back() {
      // if (this.id !== undefined) {
      //返回至详情页
      this.$router.go(-1);
      // } else {
      //   //返回至主页
      //   if (isMobile() && window.qing.isSupportNativeJsBridge) {
      //     setTimeout(() => {
      //       window.qing.call("closeWebView");
      //     }, 900);
      //   } else {
      //     this.$router.replace("/home");
      //   }
      // }
    },
    //移动邮件后，据王峰解释该邮件会被outlook删除，  直接返回主页算了
    afterMove() {
      if (this.id !== undefined) {
        //从详情页进来 返回至主页 closeWebView
        if (isMobile() && window.qing.isSupportNativeJsBridge) {
          setTimeout(() => {
            window.qing.call("closeWebView");
          }, 900);
        } else {
          this.$router.replace("/home");
        }
      } else {
        //从主页进来的 返回至主页 用go（-1）

        this.$router.go(-1);
      }
    },
    dialogPop() {
      Dialog.confirm({
        message: this.$lang.moveToInbox,
        confirmButtonText: this.$lang.yes,
        cancelButtonText: this.$lang.no,
        className: "errSelfDialog",
      })
        .then(() => {
          this.moveToInbox();
        })
        .catch(() => {});
    },
    async moveToInbox() {
      let arrIds = [];
      if (this.id !== undefined) {
        arrIds.push(this.id);
      } else {
        arrIds = this.checkboxSelectArr;
      }

      try {
        const res = await this.Api.batchMove({
          folderId: "inbox",
          ids: arrIds,
        });
        const { success } = res?.data;
        if (success) {
          this.$imbedapi(666001004, "moveMail").then((res) =>
            console.warn(res, "邮件移动")
          );
          this.$toast.success(this.$lang.successMove);
          this.showBoxGroup = false;
          this.SAVECHECKBOXSELECTARR([]);
          this.afterMove();
          // this.back();
        }
      } catch {
        console.error("批量移动失败");
      }
    },
    toggleTree() {
      this.isOpen = !this.isOpen;
      this.getChildFolder();
    },

    async getChildFolder() {
      try {
        const res = await this.Api.listChildFolder("inbox");
        const { success, data } = res?.data;
        if (success) {
          this.inboxChildFolder = data.length ? data : {};
        }
      } catch {
        console.error("获取收件箱子文件夹失败");
      }
    },
    async getCurrentFolder() {
      this.$toast.loading({
        message: this.$lang.loading,
        forbidClick: true,
        duration: 0,
      });
      try {
        const res = await this.Api.listCurrentFolder();
        this.$toast.clear()
        const { success, data } = res?.data;
        if (success) {
          // console.warn("data", data);
          let folderTree = data;
          const inboxData = data.find(
            (item) => item.displayName === this.$lang.inbox
          );
          // console.warn('inboxDta',inboxData)
          this.inboxChildFolderCount = inboxData.childFolderCount;
          console.warn('inboxChildFolderCount',this.inboxChildFolderCount)
          this.sortFolderInSpecifiedOrder(folderTree);
        }
      } catch(err) {
         console.log(err);
        console.error("获取当前文件夹失败");
       
      }
    },
  },
  created() {
    this.getCurrentFolder();
  },
};
</script>

<style lang="less" scoped>
.page {
  height: 100%;
  width: 100%;
  font-size: 16px;
  padding: 0 20px 0 16px;
  overflow: auto;
  .header {
    width: 100%;
    height: 44px;
    line-height: 44px;
    position: relative;
    clear: both;
    h4 {
      text-align: center;
      font-size: 18px;
      font-weight: 500;
    }
    span {
      position: absolute;
      top: 0;
      right: 0;
      font-size: 16px;
    }
  }
  .myFolder {
    display: flex;
    flex-direction: column;

    .inboxTitle-wrapper {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;

      .left-side {
        display: flex;
        height: 56px;
        justify-content: flex-start;
        width: 90%;
        .left-side-icon {
          width: 24px;
          margin-right: 16px;
          pointer-events: none;
        }
        p {
          line-height: 56px;
        }
      }
      .right-side {
        display: flex;
        align-items: center;
        .unreadCount {
          font-size: 14px;
          color: #969799;
          font-weight: 400;
          margin-right: 8px;
        }
        .right-icon-wraper {
          line-height: 56px;
          img{
            pointer-events: none;
          }
        }
      }
    }
    .inboxSubFolder {
      padding-left: 1rem;
    }
  }
  .folderTree {
    padding-bottom: 100px;
  }
}
</style>
